<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <title>example</title>
</head>
<body>
<div id="app">
    <input id="txt" type="text" placeholder="说点什么…" name="msg">
    <button onclick="sendMsg()">发送</button>
    <ul id="log"></ul>
</div>
<script src="https://cdn.jsdelivr.net/npm/socket.io@4.8.1/client-dist/socket.io.min.js" defer></script>

<script defer>


    window.onload = () => {
        socket = io();
        socket.on('connect', () => {
            appendLog('系统', '已连接到服务器');
        });


        const appendLog = (who, msg) => {
            const li = document.createElement('li');
            li.textContent = `[${who}] ${msg}`;
            document.getElementById('log').prepend(li);
        }


        const sendMsg = () => {
            let msg = document.querySelector('input[name=msg]').value
            appendLog('我', msg)
            socket.emit('message', {msg});
            document.querySelector('input[name=msg]').value = '';
        }


        socket.on('response1', (payload) => {
            appendLog('response1', payload.message);
        });

        socket.on('response2', (payload) => {
            appendLog('response2', payload.message);
        });

        window.sendMsg = sendMsg;
    }

</script>
</body>
</html>